<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>模板</title>
        
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Microsoft/vscode/extensions/markdown-language-features/media/markdown.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Microsoft/vscode/extensions/markdown-language-features/media/highlight.css">
        
        <style>
.task-list-item { list-style-type: none; } .task-list-item-checkbox { margin-left: -20px; vertical-align: middle; }
</style>
        <style>
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe WPC', 'Segoe UI', 'Ubuntu', 'Droid Sans', sans-serif;
                font-size: 14px;
                line-height: 1.6;
            }
        </style>
        
        
    </head>
    <body class="vscode-light">
        <h2 id="%e6%a8%a1%e6%9d%bf">模板</h2>
<ul>
<li><a href="#%e6%a8%a1%e6%9d%bf">模板</a>
<ul>
<li><a href="#1-%e4%bb%80%e4%b9%88%e6%98%af%e6%a8%a1%e6%9d%bf">1 什么是模板</a>
<ul>
<li><a href="#11-what">1.1 what</a></li>
<li><a href="#12-%e5%a6%82%e4%bd%95%e4%bd%bf%e7%94%a8%e6%a8%a1%e6%9d%bf">1.2 如何使用模板</a></li>
</ul>
</li>
<li><a href="#2-%e6%a8%a1%e6%9d%bf%e8%af%ad%e6%b3%95">2 模板语法</a>
<ul>
<li><a href="#21-%e4%b8%80%e4%b8%aa%e6%af%94%e8%be%83%e5%a4%a7%e7%9a%84%e4%be%8b%e5%ad%90">2.1 一个比较大的例子</a></li>
<li><a href="#22-%e5%9f%ba%e6%9c%ac%e7%9a%84%e5%bd%a2%e5%bc%8f">2.2 基本的形式</a></li>
<li><a href="#23-%e5%8f%98%e9%87%8f">2.3 变量</a></li>
<li><a href="#24-%e5%8f%98%e9%87%8f%e4%b8%8e%e8%bf%87%e6%bb%a4%e5%99%a8">2.4 变量与过滤器</a></li>
<li><a href="#25-%e5%be%aa%e7%8e%af">2.5 循环</a></li>
<li><a href="#26-if">2.6 if</a></li>
<li><a href="#27-%e5%85%b6%e4%bb%96%e6%a0%87%e7%ad%betag%e5%91%bd%e4%bb%a4">2.7 其他标签|tag|命令</a>
<ul>
<li><a href="#1-static">1 static</a></li>
<li><a href="#2-url-%e7%b1%bb%e4%bc%bc%e4%ba%8ereverse%e5%87%bd%e6%95%b0">2 url 类似于reverse函数</a></li>
<li><a href="#3-extentds-block">3 extentds block</a></li>
<li><a href="#4-now-displays-the-current-date-andor-time">4 <code>now</code>  Displays the current date and/or time</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#3-shell%e6%8a%80%e5%b7%a7">3 shell技巧</a></li>
</ul>
</li>
</ul>
<hr>
<h3 id="1-%e4%bb%80%e4%b9%88%e6%98%af%e6%a8%a1%e6%9d%bf">1 什么是模板</h3>
<h4 id="11-what">1.1 what</h4>
<blockquote>
<p>模板类似字符串格式化</p>
</blockquote>
<pre><code class="language-python"><div> <span class="hljs-string">'{who} likes to eat {what}'</span>.format(who=<span class="hljs-string">'lilei'</span>, what=<span class="hljs-string">'apples'</span>)
</div></code></pre>
<p>但这种字符串格式化比较简单，<code>格式</code>比较简单，传入（渲染）的<code>数据</code>也比较简单；而在网页渲染的情况下，我们的模板格式的内容是十分丰富的，传的数据可能是数组、字典等数据容器，将传入的数据渲染到模板的时候，对数据的操作可能也是多样性的，所以使用简单的字符串格式化不太能够满足需求，才有了模板引擎以及模板语法。</p>
<p>记住这个公式：
<code>我们看到的页面 =  模板 + 数据</code></p>
<p>模板就是定制的html页面显示形式，并且将里面的数据抽取出来，采用变量的形式来对数据进行操作展示。</p>
<h4 id="12-%e5%a6%82%e4%bd%95%e4%bd%bf%e7%94%a8%e6%a8%a1%e6%9d%bf">1.2 如何使用模板</h4>
<p>采用**渲染页面（模板+数据）**的方式</p>
<p>在视图中进行页面的渲染，如下</p>
<pre><code class="language-python"><div><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">cx</span><span class="hljs-params">(request)</span>:</span>
    <span class="hljs-keyword">return</span> render(request, 
                <span class="hljs-string">'template_path'</span>,
                 {<span class="hljs-string">'data-key'</span>:<span class="hljs-string">'data-value'</span>})
</div></code></pre>
<p>视图中一般的策略是：</p>
<ol>
<li>业务逻辑处理，计算出想要给用户返回的数据</li>
<li>采用字典的形式将数据进行封装
<ol>
<li>返回的数据可能有种，封装成key-value对的形式十分清晰直观</li>
<li>value部分，可以是str\list\dict等各种数据类型</li>
<li>模板html中，通过key名字对数据进行操作</li>
</ol>
</li>
<li>使用render将html模板与数据进行渲染（将数据按照模板中的规则生产出具体的页面）</li>
</ol>
<hr>
<h3 id="2-%e6%a8%a1%e6%9d%bf%e8%af%ad%e6%b3%95">2 模板语法</h3>
<p>所谓模板语法，就是解决<code>“如何将各种类型的数据以各种个性化的方式定制到html”</code>问题的解决方案。</p>
<p>所以学模板语法时，我们首先要认识到目标问题可以试一下几种情况：</p>
<ul>
<li>如何将字符串插入到html文档中</li>
<li>如何根据传入的列表数据，来生成一个 <code>ul &gt; li</code> 这样的html列表</li>
<li>如何获得传入的对象数据的某个属性</li>
<li>如何根据传入的[obj,obj,...]，来生成一个表格table</li>
<li>...</li>
</ul>
<h4 id="21-%e4%b8%80%e4%b8%aa%e6%af%94%e8%be%83%e5%a4%a7%e7%9a%84%e4%be%8b%e5%ad%90">2.1 一个比较大的例子</h4>
<pre><code class="language-django"><div><span class="xml"></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">extends</span></span> "base_generic.html" %}</span><span class="xml">

</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">block</span></span> title %}</span><span class="xml"></span><span class="hljs-template-variable">{{ section.title }}</span><span class="xml"></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endblock</span></span> %}</span><span class="xml">

</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">block</span></span> content %}</span><span class="xml">
<span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span></span><span class="hljs-template-variable">{{ section.title }}</span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">for</span></span> story <span class="hljs-keyword">in</span> story_list %}</span><span class="xml">
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"</span></span></span><span class="hljs-template-variable">{{ story.get_absolute_url }}</span><span class="xml"><span class="hljs-tag"><span class="hljs-string">"</span>&gt;</span>
    </span><span class="hljs-template-variable">{{ story.headline|<span class="hljs-name">upper</span> }}</span><span class="xml">
  <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span></span><span class="hljs-template-variable">{{ story.tease|<span class="hljs-name">truncatewords</span>:<span class="hljs-string">"100"</span> }}</span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endfor</span></span> %}</span><span class="xml">
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endblock</span></span> %}</span><span class="xml">
</span></div></code></pre>
<h4 id="22-%e5%9f%ba%e6%9c%ac%e7%9a%84%e5%bd%a2%e5%bc%8f">2.2 基本的形式</h4>
<ul>
<li><code>{{ var }}</code> 两个大括号用来插值（用变量的值来代替）</li>
<li><code>{{ var | filter }}</code> 过滤器, 类似于一个函数，对前面的变量进行处理，把结果进行输出</li>
<li><code>{% for/if %}</code> 大括号里百分号，表示指令标签 （循环、分支等）</li>
<li><code>{# #}</code> 注释</li>
</ul>
<h4 id="23-%e5%8f%98%e9%87%8f">2.3 变量</h4>
<ul>
<li><code>{{ list.0 }}</code> 相当于python中的list[0]</li>
<li><code>{{ dict.items }}</code> 相当python中的dict.items()</li>
</ul>
<p>标量中的点用法很多，可以表示以下情况：</p>
<ul>
<li>字典查询（Dictionary lookup）</li>
<li>属性或方法查询（Attribute or method lookup）</li>
<li>数字索引查询（Numeric index lookup）</li>
</ul>
<h4 id="24-%e5%8f%98%e9%87%8f%e4%b8%8e%e8%bf%87%e6%bb%a4%e5%99%a8">2.4 变量与过滤器</h4>
<p>过滤器类似于函数对变量进行处理，输出结果。</p>
<p>Django内置了一些过滤器，可以参考这个链接：<a href="https://docs.djangoproject.com/en/3.0/ref/templates/builtins/">https://docs.djangoproject.com/en/3.0/ref/templates/builtins/</a></p>
<p>我们可以根据变量的类型，来列举一下常用的过滤器</p>
<ul>
<li>通用的
<ul>
<li>default  default_if_none</li>
<li>length</li>
<li>add</li>
</ul>
</li>
<li>字符串
<ul>
<li>capfirst upper lower title</li>
<li>center</li>
<li>cut</li>
<li>escape</li>
<li>linebreaks linebreaksbr</li>
<li>striptags</li>
<li>linenumbers</li>
<li>ljust rjust</li>
<li>make_list</li>
</ul>
</li>
<li>数值
<ul>
<li>floatformat</li>
</ul>
</li>
<li>布尔值
<ul>
<li>yesno</li>
</ul>
</li>
<li>日期
<ul>
<li>date  Y-m-d H:i:s</li>
<li>time</li>
</ul>
</li>
<li>列表
<ul>
<li>first</li>
<li>slice</li>
<li>join</li>
<li>random</li>
<li>unordered_list</li>
</ul>
</li>
<li>字典
<ul>
<li>dictsort # Takes a list of dictionaries and returns that list sorted by the key given in the argument.</li>
<li></li>
</ul>
</li>
</ul>
<h4 id="25-%e5%be%aa%e7%8e%af">2.5 循环</h4>
<pre><code class="language-django"><div><span class="xml"></span><span class="hljs-template-tag">{%<span class="hljs-name"><span class="hljs-name">for</span></span> poem <span class="hljs-keyword">in</span> poems %}</span><span class="xml">
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span></span><span class="hljs-template-variable">{{ poem.title}}</span><span class="xml"> <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endfor</span></span> %}</span><span class="xml">

</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">for</span></span> key, value <span class="hljs-keyword">in</span> data.items %}</span><span class="xml">
    </span><span class="hljs-template-variable">{{ key }}</span><span class="xml">: </span><span class="hljs-template-variable">{{ value }}</span><span class="xml">
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endfor</span></span> %}</span><span class="xml">

<span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">for</span></span> athlete <span class="hljs-keyword">in</span> athlete_list %}</span><span class="xml">
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span></span><span class="hljs-template-variable">{{ athlete.name }}</span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">empty</span></span> %}</span><span class="xml">
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Sorry, no athletes in this list.<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endfor</span></span> %}</span><span class="xml">
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</span></div></code></pre>
<table>
<thead>
<tr>
<th>Variable</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>forloop.counter</td>
<td>The current iteration of the loop (1-indexed)</td>
</tr>
<tr>
<td>forloop.counter0</td>
<td>The current iteration of the loop (0-indexed)</td>
</tr>
<tr>
<td>forloop.revcounter</td>
<td>The number of iterations from the end of the loop (1-indexed)</td>
</tr>
<tr>
<td>forloop.revcounter0</td>
<td>The number of iterations from the end of the loop (0-indexed)</td>
</tr>
<tr>
<td>forloop.first</td>
<td>True if this is the first time through the loop</td>
</tr>
<tr>
<td>forloop.last</td>
<td>True if this is the last time through the loop</td>
</tr>
<tr>
<td>forloop.parentloop</td>
<td>For nested loops, this is the loop surrounding the current one</td>
</tr>
</tbody>
</table>
<h4 id="26-if">2.6 if</h4>
<pre><code class="language-django"><div><span class="xml"></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">if</span></span> isadmin %}</span><span class="xml">
   admin functions
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">elif</span></span> isuser %}</span><span class="xml">
    user functions
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">else</span></span> %}</span><span class="xml">
    please login 
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endif</span></span> %}</span><span class="xml">
</span></div></code></pre>
<h4 id="27-%e5%85%b6%e4%bb%96%e6%a0%87%e7%ad%betag%e5%91%bd%e4%bb%a4">2.7 其他标签|tag|命令</h4>
<h5 id="1-static">1 static</h5>
<pre><code class="language-django"><div><span class="xml"></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">load</span></span> static %}</span><span class="xml">
<span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"</span></span></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">static</span></span> "images/hi.jpg" %}</span><span class="xml"><span class="hljs-tag"><span class="hljs-string">"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Hi!"</span>&gt;</span>

</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">load</span></span> static %}</span><span class="xml">
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">static</span></span> "images/hi.jpg" <span class="hljs-keyword">as</span> myphoto %}</span><span class="xml">
<span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"</span></span></span><span class="hljs-template-variable">{{ myphoto }}</span><span class="xml"><span class="hljs-tag"><span class="hljs-string">"</span>&gt;</span>


<span class="hljs-comment">&lt;!-- STATIC_URL in settings.py --&gt;</span>
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">load</span></span> static %}</span><span class="xml">
<span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"</span></span></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">get_static_prefix</span></span> %}</span><span class="xml"><span class="hljs-tag"><span class="hljs-string">images/hi.jpg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Hi!"</span>&gt;</span>
</span></div></code></pre>
<h5 id="2-url-%e7%b1%bb%e4%bc%bc%e4%ba%8ereverse%e5%87%bd%e6%95%b0">2 url 类似于reverse函数</h5>
<pre><code class="language-django"><div><span class="xml"></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">url</span></span> 'some-url-name' v1 v2 %}</span><span class="xml">
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">url</span></span> 'some-url-name' arg1=v1 arg2=v2 %}</span><span class="xml">

<span class="hljs-comment">&lt;!-- in urls.py --&gt;</span>
path('client/<span class="hljs-tag">&lt;<span class="hljs-name">int:id</span>&gt;</span>/', app_views.client, name='app-views-client')
<span class="hljs-comment">&lt;!-- in template --&gt;</span>
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">url</span></span> 'app-views-client' client.id %}</span><span class="xml">

<span class="hljs-comment">&lt;!-- use as --&gt;</span>
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">url</span></span> 'some-url-name' arg arg2 <span class="hljs-keyword">as</span> the_url %}</span><span class="xml">
<span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"</span></span></span><span class="hljs-template-variable">{{ the_url }}</span><span class="xml"><span class="hljs-tag"><span class="hljs-string">"</span>&gt;</span>I'm linking to </span><span class="hljs-template-variable">{{ the_url }}</span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</span></div></code></pre>
<h5 id="3-extentds-block">3 extentds block</h5>
<ul>
<li>extends  extends a parent template.</li>
<li>block Defines a block that can be overridden by child templates.</li>
</ul>
<h5 id="4-now-displays-the-current-date-andor-time">4 <code>now</code>  Displays the current date and/or time</h5>
<pre><code class="language-django"><div><span class="xml">It is </span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">now</span></span> "j m Y H:i" %}</span><span class="xml">
</span></div></code></pre>
<h5 id="5-with">5 with</h5>
<pre><code class="language-django"><div><span class="xml"></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">with</span></span> total=business.employees.count %}</span><span class="xml">
    </span><span class="hljs-template-variable">{{ total }}</span><span class="xml"> employee</span><span class="hljs-template-variable">{{ total|<span class="hljs-name">pluralize</span> }}</span><span class="xml">
</span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">endwith</span></span> %}</span><span class="xml">
</span></div></code></pre>
<h5 id="6-include">6 include</h5>
<p>Loads a template and renders it with the current context. This is a way of “including” other templates within a template.</p>
<pre><code class="language-django"><div><span class="xml"></span><span class="hljs-template-tag">{% <span class="hljs-name"><span class="hljs-name">include</span></span> "foo/bar.html" %}</span><span class="xml">
</span></div></code></pre>
<hr>
<h3 id="3-shell%e6%8a%80%e5%b7%a7">3 shell技巧</h3>
<p>可以在shell中测试模板语法</p>
<pre><code class="language-python"><div><span class="hljs-meta">&gt;&gt;&gt; </span>python manange.py shell <span class="hljs-comment">#进入该django项目的环境</span>

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> django.template <span class="hljs-keyword">import</span> Context, Template

<span class="hljs-meta">&gt;&gt;&gt; </span>t = Template(<span class="hljs-string">'My name is {{ name }}.'</span>)

<span class="hljs-meta">&gt;&gt;&gt; </span>c = Context({<span class="hljs-string">'name'</span>: <span class="hljs-string">'Gregory'</span>})

<span class="hljs-meta">&gt;&gt;&gt; </span>t.render(c)

<span class="hljs-string">'My name is Gregory.'</span>

</div></code></pre>

    </body>
    </html>